package org.openjsonp.json;

import java.math.BigDecimal;
import java.math.BigInteger;

import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;

/**
 * Implementation of interface {@link javax.json.JsonObjectBuilder
 * JsonObjectBuilder}
 * 
 */
public class JsonObjectBuilderImpl implements JsonObjectBuilder {

	private JsonObject jsonObject;

	/**
	 * Default constructor.
	 */
	public JsonObjectBuilderImpl() {
		jsonObject = new JsonObjectImpl();
	}

	@Override
	public JsonObjectBuilder add(String name, JsonValue value) {
		checkName(name);
		checkValue(value);
		jsonObject.put(name, value);
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, String value) {
		checkName(name);
		checkValue(value);
		jsonObject.put(name, new JsonStringImpl(value));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, BigInteger value) {
		checkName(name);
		checkValue(value);
		jsonObject.put(name, new JsonNumberImpl(value));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, BigDecimal value) {
		checkName(name);
		checkValue(value);
		jsonObject.put(name, new JsonNumberImpl(value + ""));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, int value) {
		checkName(name);
		jsonObject.put(name, new JsonNumberImpl(value));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, long value) {
		checkName(name);
		jsonObject.put(name, new JsonNumberImpl(value));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, double value) {
		checkName(name);
		jsonObject.put(name, new JsonNumberImpl(value));
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, boolean value) {
		checkName(name);

		JsonValue jsonValue;

		if (value) {
			jsonValue = JsonValue.TRUE;
		}
		else {
			jsonValue = JsonValue.FALSE;
		}

		jsonObject.put(name, jsonValue);

		return this;
	}

	@Override
	public JsonObjectBuilder addNull(String name) {
		checkName(name);
		jsonObject.put(name, JsonValue.NULL);
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, JsonObjectBuilder builder) {
		checkName(name);
		jsonObject.put(name, builder.build());
		return this;
	}

	@Override
	public JsonObjectBuilder add(String name, JsonArrayBuilder builder) {
		checkName(name);
		jsonObject.put(name, builder.build());
		return this;
	}

	@Override
	public JsonObject build() {
		return jsonObject;
	}

	private void checkName(String name) {
		if (name == null) {
			throw new NullPointerException("The specified name is null.");
		}
	}

	private void checkValue(Object value) {
		if (value == null) {
			throw new NullPointerException("The specified value is null.");
		}
	}
}
